package com.hong.chapter9;


import java.util.stream.Stream;

/**
 * 多线程生产者消费者关系
 */
public class ProduceConsumerVersion3 {

    private int i = 1;

    final  private Object LOCK = new Object();

    private volatile boolean isProduced = false;

    private void produce(){
        synchronized (LOCK){

            while (isProduced){
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
                System.out.println("P->"+(i++));
                LOCK.notifyAll();
                isProduced=true;


        }
    }

    private void consume(){
        synchronized (LOCK){

            while (!isProduced){
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("C->"+i);
            isProduced=false;
            LOCK.notifyAll();


        }
    }

    public static void main(String[] args) {
        ProduceConsumerVersion3 pc = new ProduceConsumerVersion3();
        Stream.of("p1","p2","p3").forEach(n->{
            new Thread("P"){
                @Override
                public void run() {
                    while (true){
                        pc.produce();
                    }

                }
            }.start();
        });

        Stream.of("C1","C2","c3","c4").forEach(n->{
            new Thread("C"){
                @Override
                public void run() {
                    while (true){
                        pc.consume();
                    }

                }
            }.start();
        });

    }
}
